import { remoteAudit } from "./remoteAudit.js";
/**
 * 对包本身进行审计，返回审计结果
 * 包本身主要是通过调用 npm 接口地址进行审计，返回的格式和 npm audit 字段有点不一样,这个包审计目的是为了检查发布为 npm 包的依赖审计，如果本身项目，调用返回会是 null
 * // remoteAudit 返回的数据结构：
{
  "advisories": {
    "123": {
      "id": 123, // ← 这个"123"是安全咨询ID
      "title": "Prototype Pollution",
      "severity": "high",
      "vulnerable_versions": "<4.17.21",
      "cwe": "CWE-400",
      "cvss": { "score": 7.5 },
      "url": "https://npmjs.com/advisories/123"
    }
  },
 */

const severityLevelsMap = {
    info: 0,
    low: 1,
    moderate: 2,
    high: 3,
    critical: 4,
};

// 添加当前工程的审计结果
export async function currentAudit(name, version) {
    const auditResult = await remoteAudit(name, version);

    // 2. 规格化审计结果
    if (
        !auditResult.advisories ||
        Object.keys(auditResult.advisories).length === 0
    ) {
        return null;
    }

    const result = {
        name,
        version,
        nodes: ['.'],
        depChains: []
    }

    const advisories = Object.values(auditResult.advisories);
    let maxSeverity = 'info'
    // 格式化输出
    result.problems = advisories.map(advisory => {
        const problem = {
            source: advisory.id,
            name,
            dependency: name,
            title: advisory.title,
            url: advisory.url,
            severity: advisory.severity,
            cwe: advisory.cwe,
            cvss: advisory.cvss,
            range: advisory.vulnerable_versions
        }

        if (severityLevelsMap[advisory.severity] > severityLevelsMap[maxSeverity]) {
            maxSeverity = advisory.severity
        }

        return problem
    })

    result.severity = maxSeverity

    return result

}